const aedes = require('aedes')();
const net = require('net');

const express = require('express'); // 引入Express用于创建HTTP服务器
const os = require('os');
const cors = require('cors');
const path = require('path'); // 用于处理文件路径
const port = 1883;
const httpPort = 3000; // HTTP服务器监听端口
const staticHttpPort = 3001; // 静态文件服务监听端口

// 认证回调函数
aedes.authenticate = (client, username, password, callback) => {
  // 在这里实现你的认证逻辑
  // 如果认证成功，调用 callback(null, true)
  // 如果认证失败，调用 callback(null, false)
  
  // 示例：允许所有连接（仅用于测试，请替换为实际认证逻辑）
  callback(null, true);
};

// 监听连接事件
aedes.on('client', client => {
  console.log(`Client connected: ${client.id}`);
});

// 监听断开连接事件
aedes.on('clientDisconnect', client => {
  console.log(`Client disconnected: ${client.id}`);
});

// 监听订阅事件
aedes.on('subscribe', (subscriptions, client) => {
  console.log(`Client ${client.id} subscribed to topics:`, subscriptions.map(s => s.topic));
});

// 监听取消订阅事件
aedes.on('unsubscribe', (topics, client) => {
  console.log(`Client ${client.id} unsubscribed from topics:`, topics);
});

// 监听消息发布事件
aedes.on('publish', (packet, client) => {
  if (client) {
    console.log(`Message received from client ${client.id}: ${packet.topic} ${packet.payload.toString()}`);
  } else {
    console.log(`Message received from server: ${packet.topic} ${packet.payload.toString()}`);
  }
});

// 创建TCP服务器并绑定Aedes实例
const server = net.createServer(aedes.handle);


// 获取本机IP地址
function getIPAddress() {
  const interfaces = os.networkInterfaces();
  for (const devName in interfaces) {
    const iface = interfaces[devName];
    for (let alias of iface) {
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
  return 'Unable to determine IP address';
}

// 启动MQTT服务器
server.listen(port, () => {
  const ip = getIPAddress();
  console.log(`MQTT server started on IP: ${ip}, port: ${port}`);
});


// 创建Express应用
const app = express();

app.use(cors());
// 设置中间件解析JSON体
app.use(express.json());

// API端点：发布消息到指定主题
app.post('/api/publish', (req, res) => {
  const { topic, message } = req.body;

  if (!topic || !message) {
    return res.status(400).send({ error: 'Topic and message are required.' });
  }

  aedes.publish({
    topic,
    payload: Buffer.from(message),
    retain: false,
    qos: 0
  }, () => {
    res.send({ success: true });
  });
});

// API端点：订阅主题（注意：这将仅适用于HTTP长轮询或其他形式的一次性订阅）
app.get('/api/subscribe/:topic', (req, res) => {
  const topic = req.params.topic;

  // 创建一次性订阅，接收一条消息后取消订阅
  const subscription = aedes.subscribe(topic, (packet, client) => {
    if (client && packet.topic === topic) {
      res.json({ topic: packet.topic, message: packet.payload.toString() });
      aedes.unsubscribe(topic, subscription);
      subscription.removeAllListeners();
    }
  });

  // 如果在一定时间内没有收到消息，则返回超时信息
  setTimeout(() => {
    if (!res.headersSent) {
      res.status(204).send('No messages received within timeout period.');
      aedes.unsubscribe(topic, subscription);
      subscription.removeAllListeners();
    }
  }, 30000); // 例如，设置为30秒超时
});

// 启动HTTP服务器
app.listen(httpPort, () => {
  console.log(`HTTP server started on port ${httpPort}`);
});

// 创建新的Express应用用于静态文件服务
const staticApp = express();

// 使用静态文件中间件，告诉Express在接收到请求时从哪个目录提供静态文件
staticApp.use(express.static(path.join(__dirname)));

// 当访问根路径时返回index.html
staticApp.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

// 启动静态文件服务HTTP服务器
staticApp.listen(staticHttpPort, () => {
  console.log(`Static files server started on port ${staticHttpPort}`);
});